<?php

declare(strict_types=1);

namespace Plugin\Attractions\HaiKang\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\HaiKang\Model\HkDeviceChannel;

class DeviceChannelRepository extends IRepository
{
    public function __construct(protected readonly HkDeviceChannel $model) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'deviceSerial'), static function (Builder $query, $deviceSerial) {
                $query->whereIn('device_serial', Arr::wrap($deviceSerial));
            })
            ->when(Arr::get($params, 'channelId'), static function (Builder $query, $channelId) {
                $query->whereIn('channel_id', Arr::wrap($channelId));
            })
            ->when(Arr::get($params, 'channelName'), static function (Builder $query, $channelName) {
                $query->where('channel_name', 'like', "%{$channelName}%");
            })
            ->when(Arr::get($params, 'channelNo'), static function (Builder $query, $channelNo) {
                $query->whereIn('channel_no', Arr::wrap($channelNo));
            })
            ->when(Arr::get($params, 'channelStatus'), static function (Builder $query, $channelStatus) {
                $query->whereIn('channel_status', Arr::wrap($channelStatus));
            })
            ->when(Arr::get($params, 'channelType'), static function (Builder $query, $channelType) {
                $query->whereIn('channel_type', Arr::wrap($channelType));
            })
            ->when(Arr::get($params, 'isUse'), static function (Builder $query, $isUse) {
                $query->whereIn('is_use', Arr::wrap($isUse));
            })
            ->when(Arr::get($params, 'ipcSerial'), static function (Builder $query, $ipcSerial) {
                $query->whereIn('ipc_serial', Arr::wrap($ipcSerial));
            })
            ->when(Arr::get($params, 'childDeviceModel'), static function (Builder $query, $childDeviceModel) {
                $query->whereIn('child_device_model', Arr::wrap($childDeviceModel));
            });
    }

    public function list(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->get([
                'device_serial',
                'channel_id',
                'channel_name',
                'channel_no',
                'channel_status',
                'channel_type',
                'is_use',
                'ipc_serial',
                'child_device_model'
            ]);
    }
}
